package com.itheima.search.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.common.contants.RabbitMQConstants;
import com.itheima.question.pojo.Question;
import com.itheima.search.feign.QuestionFeignApi;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class Load2ESListener {
    @Autowired
    QuestionFeignApi questionFeignApi;

    private RestHighLevelClient client;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name= RabbitMQConstants.QUEUE_ES),
            exchange = @Exchange(name = RabbitMQConstants.EXCHANGE_QUESTION,type = ExchangeTypes.TOPIC),
            key = {RabbitMQConstants.ROUTING_KEY_ES}
    ))
    public void loadQuestionToEs(String questionId)throws IOException {
        Question question = questionFeignApi.queryById(questionId);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(
                new IndexRequest("st_question").id(question.getId().toString()).source(JSON.toJSONString(question), XContentType.JSON));
        this.client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("导入问题到索引库"+question);
    }
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://10.54.27.226:9200")
        ));
    }
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}
